package com.zym.community.controller;

import com.zym.community.annotation.LoginRequired;
import com.zym.community.entity.User;
import com.zym.community.service.FollowService;
import com.zym.community.service.LikeService;
import com.zym.community.service.UserService;
import com.zym.community.util.CommunityConstant;
import com.zym.community.util.CommunityUtil;
import com.zym.community.util.HostHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

 import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/user")
@Api("用户接口")
public class UserController implements CommunityConstant {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @LoginRequired  //自定义注解
    @GetMapping("/setting")
    @ApiOperation("设置页面")
    public String getSettingPage(){
        return "site/setting";
    }


    @LoginRequired  //自定义注解
    @PostMapping("/upload")
    @ApiOperation("上传头像")
    public String uploadHeader(MultipartFile headerImage, Model model){
        if (headerImage == null){
            model.addAttribute("error", "您还没有选择图片。");
            return "site/setting";
        }
        String fileName = headerImage.getOriginalFilename(); //得到文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));  //得到后缀名
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error", "文件格式不正确。");
            return "site/setting";
        }

        //生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        //确定文件存放的路径
        File dest = new File(uploadPath + "/" + fileName);

        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败", e);
        }

        //更新用户头像路径
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + fileName;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    @GetMapping("/header/{fileName}")
    @ApiOperation("获取头像")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];  //缓冲区
            int b = 0;  //标志位
            while ((b = fis.read(buffer)) != -1){  //读取文件内容到缓冲区
                os.write(buffer, 0, b);  //输出
            }
        } catch (IOException e) {
            logger.error("读取头像失败：" + e.getMessage());
        }
    }

    @PostMapping("/updatePassword")
    @ApiOperation("更新密码")
    public String updatePassword(String oldPassword, String newPassword, Model model){
        //判断是否为空
        if (StringUtils.isBlank(oldPassword)){
            model.addAttribute("oldPasswordMsg", "原始密码不能为空！");
            return "site/setting";
        }
        if (StringUtils.isBlank(newPassword)){
            model.addAttribute("newPasswordMsg", "新密码不能为空！");
            return "site/setting";
        }
        //获取当前用户
        User user = hostHolder.getUser();
        //验证密码
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if (!oldPassword.equals(user.getPassword())){
            model.addAttribute("oldPasswordMsg", "原始密码不正确！");
            return "site/setting";
        }
        //更新
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        userService.updatePassword(user.getId(), newPassword);
        return "redirect:/index";
    }

    @GetMapping("/profile/{userId}")
    @ApiOperation("个人主页")
    public String getProfilePage(@PathVariable("userId") int userId, Model model){
        User user = userService.findByUserId(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在！");
        }

        // 用户信息
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 当前用户是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "site/profile";
    }
}
